package org.example.interceptor;

import com.alibaba.fastjson.JSONObject;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.example.pojo.Result;
import org.example.utils.JwtUtils;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

@Component
public class LoginCheckInterceptor implements HandlerInterceptor {
    @Override // 目标方法之前运行
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("preHandle");

        // 获取请求的url
        String url = request.getRequestURI();
        // 判断URL是否是login直接放行
        if (url.contains("login") || url.contains("register")) {
            return true;
        }

        String token = request.getHeader("token");
        if (!StringUtils.hasLength(token)) {
            Result err = Result.clientError("NOT_LOGIN");
            // 手动奖对象转化为json
            String notLogin  = JSONObject.toJSONString(err);
            response.getWriter().write(notLogin);
            return false;
        }

        try {
            Claims claims = JwtUtils.parseJwt(token);
        } catch (Exception e) {
            e.printStackTrace();
            Result err = Result.clientError("NOT_LOGIN");
            // 手动奖对象转化为json
            String notLogin  = JSONObject.toJSONString(err);
            response.getWriter().write(notLogin);
            return false;
        }
        return true;
    }

    @Override // 目标方法之后运行
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("postHandle");
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override // 试图渲染完成之后执行
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("afterCompletion");
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
